import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 每一行代码，都是改变世界的力量
 *
 * @author 郭帅
 * @date 2022/11/11 16:53
 */
public class ApplyToEitherTest {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //个异步任务，休眠2秒，保证它执行晚点
        CompletableFuture<String> first = CompletableFuture.supplyAsync(() -> {
            try {

//                Thread.sleep(2000L);
                System.out.println("执行完第一个异步任务");
            } catch (Exception e) {
                return "第一个任务异常";
            }
            return "第一个异步任务";
        });
        ExecutorService executor = Executors.newSingleThreadExecutor();
        CompletableFuture<Void> future = CompletableFuture
                //第二个异步任务
                .supplyAsync(() -> {
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            System.out.println("执行完第二个任务");
                            return "第二个任务";
                        }
                        , executor)
                //第三个任务
                .runAfterEither(first, new Runnable() {
                    @Override
                    public void run() {
                        System.out.println("----");
                    }
                });

        future.get();
        executor.shutdown();
    }
}
